package org.lq.ht.view.employee;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.lq.ht.entity.Dictionary;
import org.lq.ht.entity.Employee;
import org.lq.ht.entity.TypeID;
import org.lq.ht.service.DictionaryService;
import org.lq.ht.service.EmployeeService;
import org.lq.ht.service.impl.DictionaryServiceImpl;
import org.lq.ht.service.impl.EmployeeServiceImpl;
import org.lq.ht.util.AutoNo;
import org.lq.ht.util.CastUtil;
import org.lq.ht.util.CastUtils;
import org.lq.ht.util.ShowMessage;

import com.eltima.components.ui.DatePicker;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.awt.FlowLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class emplyeeAdd extends JFrame {

	private JPanel contentPane;
	private JTextField txt_employeeNum;
	private JTextField txt_name;
	private JTextField txt_phoneNumber;
	private JTextField txt_salary;
	private DatePicker dp;
	private JTextField txt_userName;
	private JTextField txt_password;
	private String iconPath = ""; // 存储图片路径
	private JComboBox cb_position;
	private static List<Dictionary> positionList;//将所有字典对象存入 集合中
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					emplyeeAdd frame = new emplyeeAdd();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	private Employee update_emp =null;//修改的员工对象
	private JTextPane txt_note;
	private JPanel txt_icon;
	private JLabel lbl_icon;
	/**
	 * 带参构造
	 * @param id
	 */
	public emplyeeAdd(int id) {
		this();//调用无参构造
		
		update_emp= new EmployeeServiceImpl().getById(id);
		String dir = System.getProperty("user.dir");
		txt_employeeNum.setText(CastUtils.castString(update_emp.getEmployeeNum()));
		txt_name.setText(update_emp.getName());
		txt_phoneNumber.setText(update_emp.getPhoneNumber());
		txt_salary.setText(CastUtils.castString(update_emp.getSalary()));
		String position = update_emp.getPosition();
		for (Dictionary d : positionList) {
			if(d.getName().equals(position)) {
				cb_position.setSelectedItem(d);
			}
		}
		dp.getInnerTextField().setText(CastUtil.format(update_emp.getHiredate(), CastUtil.TIME_DATE_PATTERN));
		txt_userName.setText(update_emp.getUserName());
		txt_password.setText(update_emp.getPassword());
		txt_note.setText(update_emp.getNote());
		ImageIcon icon = new ImageIcon(dir+"/"+update_emp.getIcon());//通过图片路径 拿到图片
		icon.setImage(icon.getImage().getScaledInstance(105, 105, 1)); //设置图片 宽 高  缩放比例
		lbl_icon.setIcon(icon);//将图片放在文本框里
	}
	/**
	 * Create the frame.
	 */
	public emplyeeAdd() {
		setTitle("维护员工");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 364, 457);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "\u4FE1\u606F\u6DFB\u52A0", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("员工编号：");
		lblNewLabel.setBounds(25, 24, 73, 22);
		panel.add(lblNewLabel);
		
		txt_employeeNum = new JTextField();
		txt_employeeNum.setEditable(false);
		txt_employeeNum.setBounds(108, 25, 66, 21);
		panel.add(txt_employeeNum);
		txt_employeeNum.setColumns(10);
		
		JLabel lblNewLabel_1 = new JLabel("姓名：");
		lblNewLabel_1.setBounds(25, 60, 58, 15);
		panel.add(lblNewLabel_1);
		
		txt_name = new JTextField();
		txt_name.setColumns(10);
		txt_name.setBounds(108, 56, 89, 21);
		panel.add(txt_name);
		
		JLabel lblNewLabel_2 = new JLabel("手机号：");
		lblNewLabel_2.setBounds(25, 85, 58, 15);
		panel.add(lblNewLabel_2);
		
		txt_phoneNumber = new JTextField();
		txt_phoneNumber.setColumns(10);
		txt_phoneNumber.setBounds(108, 82, 89, 21);
		panel.add(txt_phoneNumber);
		
		JLabel lblNewLabel_2_1 = new JLabel("底薪：");
		lblNewLabel_2_1.setBounds(25, 116, 58, 15);
		panel.add(lblNewLabel_2_1);
		
		txt_salary = new JTextField();
		txt_salary.setColumns(10);
		txt_salary.setBounds(108, 113, 89, 21);
		panel.add(txt_salary);
		
		JLabel lblNewLabel_2_2 = new JLabel("入职时间：");
		lblNewLabel_2_2.setBounds(23, 176, 73, 15);
		panel.add(lblNewLabel_2_2);
		
		dp = new DatePicker();
		dp.setBounds(108, 172, 137, 21);
		dp.getInnerTextField().setText(CastUtils.format(new Date()));
		panel.add(dp);
		
		JLabel lblNewLabel_3 = new JLabel("备注：");
		lblNewLabel_3.setBounds(25, 274, 58, 26);
		panel.add(lblNewLabel_3);
		
		txt_note = new JTextPane();
		txt_note.setBounds(86, 278, 159, 81);
		panel.add(txt_note);
		
		txt_icon = new JPanel();
		txt_icon.setBorder(new TitledBorder(null, "\u56FE\u7247", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		txt_icon.setBounds(210, 10, 120, 121);
		panel.add(txt_icon);
		txt_icon.setLayout(null);
		
		lbl_icon = new JLabel("双击上传");
		lbl_icon.setFont(new Font("宋体", Font.PLAIN, 13));
		lbl_icon.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {//双击事件
				if(e.getClickCount()==2) {//双击
					JFileChooser jf = new JFileChooser();
					jf.setFileFilter(new FileNameExtensionFilter("JP & PNG fiels", "jpg", "png"));
					jf.showOpenDialog(null);
					File f = jf.getSelectedFile();
					String path = f.getAbsolutePath();
					iconPath=path;//将用户路径赋值给iconPath
					ImageIcon icon = new ImageIcon(path);//通过图片路径 拿到图片
					icon.setImage(icon.getImage().getScaledInstance(105, 105, 1)); //设置图片 宽 高  缩放比例
					lbl_icon.setIcon(icon);//将图片放在文本框里
				}
				
			}
			
		});
		lbl_icon.setBounds(10, 10, 100, 101);
		txt_icon.add(lbl_icon);
		
		JLabel lblNewLabel_4 = new JLabel("职务：");
		lblNewLabel_4.setBounds(25, 142, 58, 15);
		panel.add(lblNewLabel_4);
		
		cb_position = new JComboBox();
		cb_position.setBounds(108, 139, 89, 23);
		panel.add(cb_position);
		
		JLabel lblNewLabel_5 = new JLabel("用户名：");
		lblNewLabel_5.setBounds(22, 207, 58, 15);
		panel.add(lblNewLabel_5);
		
		txt_userName = new JTextField();
		txt_userName.setBounds(109, 204, 90, 21);
		panel.add(txt_userName);
		txt_userName.setColumns(10);
		
		txt_password = new JTextField();
		txt_password.setColumns(10);
		txt_password.setBounds(109, 234, 90, 21);
		panel.add(txt_password);
		
		JLabel lblNewLabel_5_1 = new JLabel("密码：");
		lblNewLabel_5_1.setBounds(22, 237, 58, 15);
		panel.add(lblNewLabel_5_1);
		
		JPanel panel_1 = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel_1.getLayout();
		flowLayout.setHgap(10);
		contentPane.add(panel_1, BorderLayout.SOUTH);
		
		JButton btn_save = new JButton("保存");
		btn_save.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {//添加
				EmployeeService empService = new EmployeeServiceImpl();
				if(update_emp!=null) {//修改
					Employee emp = new Employee();
					update_emp.setEmployeeNum(CastUtils.castInt(AutoNo.getVipNo()));
					update_emp.setUserName(txt_userName.getText());
					update_emp.setPassword(txt_password.getText());
					update_emp.setPhoneNumber(txt_phoneNumber.getText());
					Dictionary pos = (Dictionary) cb_position.getSelectedItem();
					update_emp.setPosition(pos.getName());
					update_emp.setNote(txt_note.getText());
					update_emp.setName(txt_name.getText());
					update_emp.setSalary(CastUtils.castInt(txt_salary.getText()));
					String hiredate =dp.getInnerTextField().getText();
					try {
						emp.setHiredate(CastUtils.utilDateToSqlTimestamp(CastUtils.parse(hiredate)));
					} catch (ParseException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					if(!"".equals(iconPath)) {
						// 头像赋值
						String icon = updateImg();
						update_emp.setIcon(icon);
						System.out.println(icon);
					}
					System.out.println(empService.update(update_emp));
					ShowMessage.frameMessage(emplyeeAdd.this,empService.update(update_emp), "修改");
					dispose();					
				}else {
					
					Employee emp = new Employee();
					emp.setEmployeeNum(CastUtils.castInt(AutoNo.getVipNo()));
					emp.setUserName(txt_userName.getText());
					emp.setPassword(txt_password.getText());
					emp.setPhoneNumber(txt_phoneNumber.getText());
					Dictionary pos = (Dictionary) cb_position.getSelectedItem();
					emp.setPosition(pos.getName());
					emp.setNote(txt_note.getText());
					emp.setName(txt_name.getText());
					emp.setSalary(CastUtils.castInt(txt_salary.getText()));
					String hiredate =dp.getInnerTextField().getText();
					try {
						emp.setHiredate(CastUtils.utilDateToSqlTimestamp(CastUtils.parse(hiredate)));
					} catch (ParseException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					//头像赋值
					if(!"".equals(iconPath)) {
						String icon = updateImg();
						emp.setIcon(icon);
					}
					ShowMessage.frameMessage(emplyeeAdd.this,empService.save(emp), "保存");
					dispose();
				}
				
				
			}
		});
		btn_save.setFont(new Font("宋体", Font.PLAIN, 18));
		panel_1.add(btn_save);
		
		JButton btn_cancel = new JButton("取消");
		btn_cancel.setFont(new Font("宋体", Font.PLAIN, 18));
		panel_1.add(btn_cancel);
		
		initCombox();
	}
	
	/**
	 * 初始化下拉列表
	 */
	public void initCombox() {
		DictionaryService ds  = new DictionaryServiceImpl();
		positionList = ds.findById(TypeID.职位);
		//将指定的集合转换成数组
		DefaultComboBoxModel<Dictionary> positionDBM = new DefaultComboBoxModel<Dictionary>(positionList.toArray(new Dictionary[] {}));
		cb_position.setModel(positionDBM);
		
	}
	/**
	 * 上传图片到指定路径
	 * @return
	 */
	public String updateImg() {
		String icon="";//存放图片在当前项目文件夹下的输出路径
		//动态获取当前的项目路径
		String dir = System.getProperty("user.dir");
		File file = new File(iconPath);//拿到图片的选择路径iconPath
		String fileName = file.getName();//得到图片的名称
		InputStream is = null;
		OutputStream os = null;
		
		
		try {
			//拼接输出路径
			icon="/icons/"+System.currentTimeMillis()+"-"+fileName;
			//原图片
			is=new FileInputStream(file);
			os = new FileOutputStream(dir+icon);
			byte[] b = new byte[1024];
			int len = 0;
			while((len=is.read())!=-1) {
				os.write(b,0,len);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				os.flush();
				os.close();
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		return icon;
	}
}
